<template>
  <NavBar></NavBar>
  <div class="matchground">
    <div class="row">
      <div class="col-3 components">
        <div class="user-photo">
          <img :src="$store.state.user.photo" alt="" />
        </div>
        <div class="user-username">
          <el-icon v-if="$store.state.pk.isRoomUser" size="30"><HomeFilled /></el-icon>
          {{ $store.state.user.username }}
        </div>
      </div>

      <div class="col-2 components">
        <div v-if="$store.state.pk.botId !== '-1'" class="user-select_bot">
          <select
            v-model="select_bot"
            class="form-select"
            @change="handleBotChange"
            aria-label="Default select example"
          >
            <option value= "0" selected>简单人机</option>
            <option v-for="bot in bots" :key="bot.id" :value="bot.id.toString()">
              {{ bot.title }}
            </option>
          </select>
        </div>
      </div>

      <div class="col-3 components">
        <div class="user-photo">
          <img :src="$store.state.pk.opponentPhoto" alt="" />
        </div>
        <div class="user-username">
          <el-icon v-if="!$store.state.pk.isRoomUser" size="30" ><HomeFilled /></el-icon>
          {{ $store.state.pk.opponentUsername }}
        </div>
      </div>
      <div v-if="!$store.state.pk.isMatching && $store.state.pk.botId === '-1'" class="col-4 components">
        <InviteFriendList

          class="friend-list"
        />
      </div>

      <div class="col-8" style="text-align: center; margin-top: 14vh">
        <button
          @click="click_match_btn()"
          type="button"
          class="btn btn-secondary btn-lg"
        >
          {{ match_btn_info }}
        </button>
      </div>
      <div class="col-8" style="text-align: left; margin-top: 14vh">
        <button
            @click="click_leave_btn()"
            type="button"
            class="btn btn-secondary btn-lg"
        >
          退出
        </button>
      </div>
    </div>
  </div>
</template>

<script>
import InviteFriendList from "./InviteFriendList.vue";
import {ref, watch} from "vue";
import { useStore } from "vuex";
import NavBar from "./NavBar.vue";
import {ElMessage} from "element-plus";
// import $ from "jquery";

export default {
  components: { InviteFriendList, NavBar },

  setup() {
    const store = useStore(); //拿出全局变量
    let match_btn_info = ref("")
    let bots = ref([]);
    let select_bot = ref("0");

    // let showFriendList = ref(false);

    let friends = ref([]);

    const updateMatchBtnInfo = () =>{
      console.log("wce");
      if(store.state.pk.isMatching){
        match_btn_info.value = "开始匹配";
      }
      else if (store.state.pk.isRoomUser) {
        match_btn_info.value = store.state.pk.isReady ? "开始游戏" : "等待对手准备";
      } else {
        match_btn_info.value = store.state.pk.isReady ? "取消准备" : "准备";
      }
    }

    updateMatchBtnInfo();

    watch(
        () => store.state.pk.isReady,
        () => {
            console.log("watch到了",store.state.pk.isReady)
            updateMatchBtnInfo();
        }
    );

    // 新增的方法，用于处理AI选择变化
    const handleBotChange = () => {
      console.log("Selected bot ID:", select_bot.value);
      if(select_bot.value === "0"){
        store.commit("updateOpponent",{
          username:"G7人",
          photo:"https://cdn.acwing.com/media/article/image/2024/12/31/134627_0bdcf210c7-OIP-C.jpg",
          id:-10,
        })
      }
      else if(select_bot.value === "1"){
        store.commit("updateOpponent",{
          username:"普通人机",
          photo:"https://cdn.acwing.com/media/article/image/2024/12/31/134627_12aeb32ec7-%E6%9C%BA%E5%99%A8%E4%BA%BA%E5%9B%BE%E7%89%87%E7%94%9F%E6%88%901.png",
          id:-10,
        })
      }
      else if(select_bot.value === "2"){
        store.commit("updateOpponent",{
          username:"AlphaGo",
          photo:"https://cdn.acwing.com/media/article/image/2024/12/31/134627_17e11b7ac7-%E6%9C%BA%E5%99%A8%E4%BA%BA%E5%9B%BE%E7%89%87%E7%94%9F%E6%88%902.png",
          id:-10,
        })
      }
      // 在这里添加你想要执行的逻辑
      // 比如更新store中的botId
      store.commit('updateBotId', select_bot.value);
    };
    // const toggleFriendList = () => {
    //   showFriendList.value = !showFriendList.value;
    // };

    // const handleSelectFriend = (friend) => {
    //   console.log("Selected friend:", friend);
    //   // 在这里可以处理选择朋友后的逻辑
    //   showFriendList.value = false; // 隐藏好友列表
    // };

    const click_leave_btn = () => {
      if(store.state.pk.isMatching){//处于匹配状态而非房间状态
        store.commit("clearAllPkInfo");
        store.state.pk.status = "loading";
      }
      else if(store.state.pk.botId === "-1"){
        store.dispatch("removeRoom",{
          token:store.state.user.token,
          success(resp) {
            // console.log("getInfo成功");
            // router.push({ name: "home" });
            store.commit("clearAllPkInfo");
            store.state.pk.status = "loading";
            ElMessage.success(resp);
          },
          error(resp) {
            store.state.pk.status = "loading";
            ElMessage.error(resp);
          },
        })
      }
      else{
        store.commit("clearAllPkInfo");
        store.state.pk.status = "loading";
      }


    };
    const click_match_btn = () => {
      console.log("点了准备");
      if (match_btn_info.value === "准备") {
        store.dispatch("roomReady",{
          token:store.state.user.token,
          status:1,
          success() {

            match_btn_info.value = "取消准备"
            // ElMessage.success(resp);//准备就不用说了
          },
          error(resp) {
            ElMessage.error(resp);
          },
        })
      }
      else if(match_btn_info.value === "取消准备")
      {
        store.dispatch("roomReady",{
          token:store.state.user.token,
          status:0,
          success() {
            match_btn_info.value = "准备"
          },
          error(resp) {
            ElMessage.error(resp);
          },
        })
      }
      else if(match_btn_info.value === "开始游戏"){
        if(store.state.pk.botId === "-1") {
          store.dispatch("startGame", {
            token: store.state.user.token,
            success() {
              /////这里留白，暂时不处理，
            },
            error(resp) {
              ElMessage.error(resp);
            },
          })
        }
        else{
          store.state.pk.iAmBlack = true;
          store.commit("updateStatus","playing");

        }
      }
      else if(match_btn_info.value === "开始匹配"){

        store.dispatch("startMatching",{
          token:store.state.user.token,
          userId:store.state.user.userId,
          rating:store.state.user.score,
          success(resp) {
            match_btn_info.value = "取消匹配";
            ElMessage.success(resp);
          },
          error(resp) {
            ElMessage.error(resp);
          },
        })
      }
      else if(match_btn_info.value === "取消匹配"){
        store.dispatch("cancelMatching",{
          token: store.state.user.token,
          userId:store.state.user.userId,
          rating:store.state.user.score,

          success(resp) {
            match_btn_info.value = "开始匹配"
            ElMessage.success(resp);
          },
          error(resp) {
            ElMessage.error(resp);
          },
        })
      }
    };


    const refresh_bots = () => {
      //刷新页面(不刷新网页)
      bots.value = [
        { id: 1, title: "普通人机" },
        { id: 2, title: "困难人机" },
      ];
    };

    refresh_bots(); //从云端获取bot(post)

    return {
      match_btn_info,
      click_match_btn,
      bots,
      select_bot,
      // showFriendList,
      friends,
      // handleSelectFriend,
      // toggleFriendList,
      click_leave_btn,
      handleBotChange
    };
  },
};
</script>

<style>
.row {
  display: flex;
  align-items: stretch; /* 确保所有列的高度一致 */
}

.components {
  /*flex: 0 0 25%; !* 每列占据父容器的25% *!*/
  height: 40vh;
}

.friendliest {
  /*flex: 0 0 75%; !* 占据父容器的75% *!*/
}

div.matchground {
  width: 80vw;
  height: 80vh;
  background: rgba(137, 207, 240, 0.5);
  margin: 60px auto;
}

div.user-photo {
  text-align: center;
  padding-top: 10vh;
}
div.user-photo > img {
  border-radius: 50%;
  width: 20vh;
  height: 20vh;
}
div.user-username {
  text-align: center;
  font-size: 24px;
  font-weight: 600;
  padding-top: 2vh;
}
div.user-select_bot {
  padding-top: 5vh;
}
div.user-select_bot > select {
  width: 60%;
  margin: 0 auto;
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5); /* 半透明背景 */
  display: flex;
  justify-content: center;
  align-items: center;
}

.modal-content {
  background-color: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.3);
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.5s;
}
.fade-enter, .fade-leave-to /* .fade-leave-active in <=2.1.8 */ {
  opacity: 0;
}
</style>
